<script setup lang="ts">
import { reactive, ref, toRefs, watch } from "vue";
import router from "@/router";
import {
  deleteCartItme,
  getCartItmeList,
  upIsChosen,
  upQuantity,
} from "@/api/cart/cartItem";
import { getUserAddressList } from "@/api/address/address";
import { ElMessage, ElMessageBox, type Action, type CheckboxValueType, type UploadFile } from "element-plus";
import type {Product,CartItem} from "@/types/index"


const tableData = ref();
const loading=ref(false)
const addressList = ref();
const checkAll = ref(false);
const isIndeterminate = ref(false);
const checkedCities = ref<CartItem[]>([]);
const selectProductNum = ref(0);
const selectPriceSnapshotNum = ref(0);
const data = reactive({
  form: <CartItem>{},
});
const { form } = toRefs(data);
// 商品增减
const handleChange = async (item: any) => {
  console.log(item);
  await upQuantity(item);
  loadCart();
};

// 初始化
async function loadCart() {
  loading.value=true
  // 获取采花车内容
  await getCartItmeList().then((response) => {
    tableData.value = response.data.data.cartItemList;
    selectPriceSnapshotNum.value=response.data.data.totalAmount;
    selectProductNum.value=response.data.data.productNum;
  });
  //获取用户地址
  await getUserAddressList().then((response) => {
    addressList.value = response.data.rows;
    if(addressList.value > 0){
    form.value.userAddressId = addressList.value.filter(
      (item: any) => item.isDefault === 0
    )[0].userAddressId
    }
  });
  // 选中状态
  checkedCities.value = tableData.value.filter((item: any) => item.isChosen === 1);

  // 全选状态
  isIndeterminate.value = checkedCities.value.length > 0 ? true : false;
  loading.value=false
}

// 全选按钮点击时
const handleCheckAllChange = async (val: CheckboxValueType) => {
  const cartItemList: any = [];
  tableData.value.forEach((item: any) => {
    cartItemList.push(item);
  });
  checkedCities.value = val ? cartItemList : [];
  isIndeterminate.value = false;
  await upIsChosen(checkedCities.value);
  loadCart();
  console.log(checkedCities.value);
};
// 普通选择
const handleCheckedCitiesChange = async (value: CheckboxValueType[]) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === tableData.value.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < tableData.value.length;
  console.log(checkedCities.value)
  await upIsChosen(checkedCities.value);
  loadCart();
};
//删除采花车商品
const deleteSumbit = async (item: any) => {
  await deleteCartItme([item.cartItemId]);
  loadCart();
};
// 删除多个按钮
const deleteSumbitS = async () => {
  const id: number[] = [];
  checkedCities.value.forEach((item: any) => {
    id.push(item.cartItemId);
  });
  await deleteCartItme(id);
  loadCart();
};
//结算按钮
const settlement = () => {
  if(checkedCities.value.length > 0 ){
    router.push("/order");
  }else{
  ElMessageBox.alert('至少选中一件商品才能去结算哦~',"提示",  {
    confirmButtonText: '好的',

  })
}
};
loadCart();
</script>
<template>
  <el-row v-if="tableData !== undefined && tableData.length > 0">
    <el-col :span="15">
      <el-space wrap>
        <el-checkbox
          v-model="checkAll"
          :indeterminate="isIndeterminate"
          @change="handleCheckAllChange"
          style="margin-left: 20px"
        >
          全选
        </el-checkbox>
        <el-popconfirm title="确定要删除吗？" @confirm="deleteSumbitS">
          <template #reference>
            <el-button :disabled="checkedCities.length > 0 ? false : true"
              >删除</el-button
            >
          </template>
        </el-popconfirm>
        <!-- <el-button>移入收藏</el-button> -->
      </el-space>

      <el-checkbox-group
        v-model="checkedCities"
        @change="handleCheckedCitiesChange"
        v-loading="loading"
      >
        <el-card v-for="item in tableData" class="cartItem">
          <el-row>
            <el-col :span="1">
              <el-checkbox :key="item" :value="item"> </el-checkbox>
            </el-col>

            <el-col :span="4">
              <div style="display: inline-block">
                <el-link
                  :href="'/product/detail/' + item.product.productId"
                  :underline="false"
                  target="_blank"
                >
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="item.product.img"
                    fit="fill"
                /></el-link></div
            ></el-col>
            <el-col :span="8">
              <div style="height: 20px">
                <el-text style="width: 200px">
                  <el-link
                    :href="'/product/detail/' + item.product.productId"
                    :underline="false"
                    target="_blank"
                  >
                    {{ item.product.name }}
                  </el-link>
                </el-text>
              </div>
              <div style="font-size: 13px; line-height: normal">
                <span>
                  <el-link
                    :href="'/product/detail/' + item.product.productId"
                    :underline="false"
                    target="_blank"
                  >
                    {{ item.product.description }}
                  </el-link>
                </span>
              </div>
            </el-col>
            <el-col :span="4">
              <el-text type="danger">
                ￥{{ Number(item.product.price).toFixed(2) }}到手价</el-text
              >
            </el-col>
            <el-col :span="4">
              <el-input-number
                style="width: 100px"
                v-model="item.quantity"
                :min="1"
                :max="100"
                @change="handleChange(item)"
            /></el-col>
            <!-- 1erer -->
            <el-col :span="3" style="text-align: right">
              <!-- <el-button link type="primary">移入收藏</el-button> -->
              <el-popconfirm title="确定要删除吗？" @confirm="deleteSumbit(item)">
                <template #reference>
                  <el-button link type="primary" icon="Delete">删除</el-button>
                </template>
              </el-popconfirm>
            </el-col>
          </el-row>
        </el-card>
      </el-checkbox-group>
    </el-col>
    <el-col :span="8" style="margin-left: 40px">
      <el-card class="card-box" v-loading="loading">
        <span style="font-size: 25px; color: red; font-weight: bold">结算</span>
        <span style="margin-left: 5px">已选择{{ selectProductNum }}件商品</span>
        <el-row>
          <el-col
            v-if="selectProductNum != 0"
            :span="24"
            style="text-align: center; margin-top: 20px; margin-bottom: 20px"
          >
            <div style="display: inline-block" v-for="item in checkedCities">
              <el-image
                style="width: 100px; height: 100px"
                :src="item.product.img"
                fit="fill"
              />
            </div>
          </el-col>
          <el-col
            v-else
            :span="24"
            style="text-align: center; margin-top: 20px; margin-bottom: 20px"
          >
            选择商品查看实际价格
          </el-col>
          <el-col :span="12">
            <span style="font-size: 25px; color: red"
              >￥{{ Number(selectPriceSnapshotNum).toFixed(2) }}</span
            >
          </el-col>
          <el-col :span="12">
            <el-button style="width: 100%; height: 40px" plain @click="settlement"
              >结算</el-button
            >
          </el-col>
        </el-row>
      </el-card>
    </el-col>
  </el-row>
  <el-row v-else>
    <el-col :span="24" style="text-align: center">
      <img style="width: 100px; height: 100px" src="@/assets/空采花车.png" fit="fill" />
      <div class="nullCart">采花车空空的哦~，去看看心仪的花花吧~</div>
      <el-button style="margin-top: 10px" @click="router.push('/home')">去采花</el-button>
    </el-col>
  </el-row>
</template>
<style lang="less">
.tableCart {
  --el-table-border-color: none;
  --el-table-row-hover-bg-color: none;
}
.nullCart {
  text-align: center;
  color: #1a1a1a;
  font-family: PingFang SC;
  font-size: 14px;
  font-weight: 500;
  line-height: 20px;
}
.cartItem {
  margin-top: 10px;
}

el-checkbox-group {
  font-size: none;
  line-height: none;
}
</style>
